<template>
	<view class="search">
		<linex></linex>
		<view class="search-item">
			<view class="search-title">
				<view class="f-color">最近搜索</view>
				<view class="iconfont icon-zu" @tap="clearHistory">
					
				</view>
			</view>
			<view v-if="searchData.length > 0">
				<view class="search-name" 
				v-for="(item,index) in searchData"
				:key="index"
				>
					{{item}}
				</view>
			</view>
			<view v-else class="search-end">暂无记录</view>
		</view>
		
		<view class="search-item">
			<view class="search-title">
				<view class="f-color">热门推荐</view>
				<view class="iconfont">
					
				</view>
			</view>
			<view class="search-name f-color">
				IDE
			</view>
			<view class="search-name f-color">
				IDE
			</view>
			<view class="search-name f-color">
				IDE
			</view>
		</view>
		
	</view>
</template>

<script>
import Linex from "@/components/common/line.vue"
	export default {
		components:{
			Linex
		},
		data() {
			return {
				// 输入的关键词
				keyword:'',
				// 搜索过的内容记录
				searchData:[]
			}
		},
		//自定义导航搜索按钮跳转
		onNavigationBarButtonTap(e) {
			if(e.float === 'right'){
				this.search()
			}
			
		},
		//软键盘搜索按钮跳转
		onNavigationBarSearchInputConfirmed() {
			this.search()
		},
		//输入框状态记录
		onNavigationBarSearchInputChanged(e) {
			this.keyword = e.text
		},
		onLoad() {
			//获取本地缓存记录，并转换为js对象格式
			uni.getStorage({
				key:"searchData",
				success: (res) => {
					this.searchData = JSON.parse(res.data)
				}
			})
		},
		methods: {
			search(){
				if(this.keyword == ''){
					return uni.showToast({
						title:"关键词为空",
						icon:"none"
					})
				}else{
					uni.navigateTo({
						url:"/pages/search-list/search-list?keyword="+this.keyword+''
					})
				}
				uni.hideKeyboard()
				this.addSearch()
			},
			// 添加数据
			addSearch(){
				// 查询数组如果已存在相同的值则不进行记录
				let idx = this.searchData.indexOf(this.keyword)
				if(idx < 0){
					this.searchData.unshift(this.keyword)
				}else{
				// 将再次查询的关键词进行删除在添加,时其出现在最开头
					this.searchData.unshift(this.searchData.splice(idx,1)[0])
				}
				// 将数据进行本地缓存，并转换为字符串
				uni.setStorage({
					key:"searchData",
					data:JSON.stringify(this.searchData)
				})
				
			},
			// 清除本地记录
			clearHistory(){
				uni.showModal({
					title:"重要提示",
					content:"是否要清除记录",
					cancelText:"取消",
					confirmText:"确定",
					success: (res) => {
					//清空缓存数据
						if(res.confirm){
							uni.removeStorage({
								key:"searchData"
							})
							this.searchData = []
						}
					}
				})
			}
		}
		
	}
</script>

<style scoped>
.search-item{
	padding: 20rpx;
}
.search-title{
	display: flex;
	justify-content: space-between;
}
.search-name{
	padding: 4rpx 24rpx;
	background-color: #E1E1E1;
	display: inline-block;
	border-radius: 26rpx;
	margin: 10rpx;
}
.search-end{
	text-align: center;
}
</style>
